package com.itheima.springbootmybatistest.controller;

import com.itheima.springbootmybatistest.common.MessageConstant;
import com.itheima.springbootmybatistest.common.Result;
import com.itheima.springbootmybatistest.domain.User;
import com.itheima.springbootmybatistest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //查询所有用户信息
    @GetMapping("/findAll")
    public Result findAll(){
        try {
            List<User>list = userService.findAll();
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    //根据id查询用户信息
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable("id") Integer id){
        try {
            User user = userService.findById(id);
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    //新增用户信息
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try {
            userService.add(user);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true,MessageConstant.ADD_USER_SUCCESS);
    }

    //根据id删除用户
    @DeleteMapping("deleteById/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        try {
            userService.deleteById(id);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
    }

    //根据id修改用户
    @PutMapping("/edit")
    public Result edit(@RequestBody User user){
        try {
            userService.update(user);
            return new Result(true,MessageConstant.UPDATE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.UPDATE_USER_FAIL);
        }
    }
}
